package com.redis.resource.config;

import com.redis.common.component.CustomOAuth2AuthenticationEntryPoint;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @description: @EnableResourceServer 实现资源服务器
 * @Author C_Y_J
 * @create 2022/1/7 11:33
 **/
@Configuration
@AllArgsConstructor
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private final TokenStore tokenStore;

    private final CustomOAuth2AuthenticationEntryPoint auth2AuthenticationEntryPoint;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http
                // 针对所有的请求
                .authorizeRequests()
                // 匹配规则：/user/{id}  不需要登录认证
                .antMatchers("/user/info/{id}").permitAll()
                // 匹配规则：任何请求 需要登录认证
                .anyRequest().authenticated();

        //允许表单登录
        http.formLogin();

        // 开启httpBasic认证
        http.httpBasic();

        // 关闭csrf防护
        http.csrf().disable();
    }


    @Primary
    @Bean
    public RemoteTokenServices remoteTokenServices() {
        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        // 设置授权服务器check_token端点完整地址
        remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:6600/oauth/check_token");
        // 设置客户端id与secret，注意：client_secret值不能使用passwordEncoder加密！
        remoteTokenServices.setClientId("client_1");
        remoteTokenServices.setClientSecret("client_1_secret");
        return remoteTokenServices;
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {

        // 设置资源服务器的资源列表
        resources.resourceId("resource");

        // 设置资源服务器的token存储
        resources.tokenStore(tokenStore);

        // 针对资源服务器的异常处理
        resources.authenticationEntryPoint(auth2AuthenticationEntryPoint);

    }
}
